<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<!doctype html>
<html>
<head>
<title>权限管理</title>
	<jsp:include page="/common/init.jsp"></jsp:include>
	<link href="${ctx}/assets/zTree/css/zTreeStyle/zTreeStyle.css" type="text/css" rel="stylesheet" />
	<script src="${ctx}/assets/zTree/js/jquery.ztree.all.js" type="text/javascript" charset="UTF-8"></script>
<script type="text/javascript">
	var INDATARIGHT = [ '', '' ];
	function hideMenu() {
		$("#deptContent").fadeOut("fast");
		$("body").unbind("mousedown", onBodyDown);
	}
	function onBodyDown(event) {
		if (!(event.target.id == "deptContent" || $(event.target).parents(
				"#deptContent").length > 0)) {
			hideMenu();
		}
	}
	var wfroleSeltedData;
	var selWfroleID = '';

	var roleTree = null;
	var rightTree = null;
	//var selUserId = "";
	var selRoleId = "";
	var selRightId = "";
	var copyNodes = null;
	var deptTree = null;
	var deptTreeNodes = null;

	function wfroleRowSeltListener() {
		var rows = $("#wfRoleTable tr");
		$.each(rows, function (index, row) {
			if (index > 0) {
				$(row).click(function () {
					wfroleSeltedData = $('#wfRoleTable').dataTable().fnGetData(this);
					var role_id = selWfroleID = wfroleSeltedData.ROLE_ID;
					var roleName = wfroleSeltedData.ROLE_NAME;
					$(row).addClass("info");
					$(row).siblings().removeClass("info");
					// 更新右侧授权列表

					getRightByRoleId(selWfroleID);
					//角色组名显示
					$(".clickedRoleNameSpan").html("<strong>" + roleName + "</strong>");

				});
			}
		});
	}

	var roleTreeSet = {
		check : {
			enable : true
		},
		data : {
			key : {
				name : "NAME"
			},
			simpleData : {
				enable : true,
				idKey : "ID",
				pIdKey : "PARENTID",
				rootPId : "-1"
			}
		},
		callback : {
			onClick : function(e, treeId, treeNode) {
				if (!treeNode.isParent) {
					//selUserId = treeNode.ID;
					selRoleId = treeNode.ID;
					//点击用户节点刷新功能树
					//getRightByUserId(selUserId);
					getRightByRoleId(selRoleId);
					if(!treeNode.checked){
						roleTree.checkNode(treeNode,true,true);
					}
				} else {
					//selUserId = "";
					selRoleId = "";
				}
			}
		}
	};

	//权限树设置
	var rightTreeSet = {
		check : {
			enable : true
		},
		data : {
			key : {
				name : "RIGHTNAME"
			},
			simpleData : {
				enable : true,
				idKey : "RIGHTID",
				pIdKey : "PARENTID",
				rootPId : "-1"
			}
		},
		callback : {
			onClick : function(e, treeId, treeNode) {
				if(!treeNode.checked){
					rightTree.checkNode(treeNode,true,true);
				}
				if (!treeNode.isParent
						&& treeNode.checked
						&& treeNode.DATARIGHT == 1) {
					var nodeOffset = $(e.target)
							.offset();
					$("#deptContent").css(
							{
								left : nodeOffset.left
										- 10 + "px",
								top : nodeOffset.top
										+ 20 + "px"
							}).slideDown("fast");
					$("body").bind("mousedown",
							onBodyDown);
					getDataRightByRoleId(selRoleId,
							treeNode);
					selRightId = treeNode.RIGHTID;
				} else {
					selRightId = "";
				}
			}
		}
	};

	var deptTreeSet = {
		check : {
			enable : true
		},
		data : {
			key : {
				name : "DEPNAME"
			},
			simpleData : {
				enable : true,
				idKey : "DEPID",
				pIdKey : "PARENTID",
				rootPId : "0000"
			}
		},
		callback : {
			onCheck : function(e, treeId, treeNode) {
				var rightNode = rightTree
						.getNodesByParam('RIGHTID',
								selRightId, null)[0];
				var treeObj = $.fn.zTree
						.getZTreeObj(treeId);
				var nodes = treeObj.getCheckedNodes();
				var dRightIDs = "", dRightNames = "";
				$.each(nodes, function(index, value) {
					if (value.DEPID != '0000') {
						dRightIDs = dRightIDs
								+ value.DEPID + ",";
						dRightNames = dRightNames
								+ value.DEPNAME + ",";
					}
				});
				if (dRightIDs.length > 1)
					dRightIDs = dRightIDs.substring(0,
							dRightIDs.length - 1);
				if (dRightNames.length > 1)
					dRightNames = dRightNames
							.substring(
									0,
									dRightNames.length - 1);
				rightNode['DATARIGHTID'] = dRightIDs;
				rightNode['DATARIGHTNAME'] = dRightNames;
				if (dRightNames.length > 1)
					rightNode['RIGHTNAME'] = rightNode.orgRightName
							+ "(" + dRightNames + ")";
				else
					rightNode['RIGHTNAME'] = rightNode.orgRightName;
				rightTree.updateNode(rightNode);
			}
		}
	};

	//根据人员id加载权限
	function getRightByRoleId(roleId) {
		if (roleId == "undefied" || roleId == "")
			return false;
		$.ajax({
			async : false,
			cache : false,
			type : 'POST',
			data : {
				roleId : roleId
			},
			dataType : "json",
			url : "${ctx}/right/getAllRoleRight",
			error : function() {
				notyError('权限数据加载失败!');
			},
			success : function(data) {
				if (rightTree != null)
					rightTree.destroy();
				$.each(data,function(index,value) {
					value['orgRightName'] = value.RIGHTNAME;
					if (value.DATARIGHTNAME != undefined && value.DATARIGHTNAME.length > 1) {
						value.RIGHTNAME = value.RIGHTNAME + "("	+ value.DATARIGHTNAME + ")";
					}
				});
				rightTree = $.fn.zTree.init($("#rightTree"),rightTreeSet, data);
				rightTree.expandAll(true);
			}
		});
	}

	//根据人员ID加载数据权限数
	function getDataRightByRoleId(roleId, rightNode) {
		if (roleId == "undefied" || roleId == "")
			return false;
		var data = deptTreeNodes;
		var dRightIDs = "";
		dRightIDs = rightNode.DATARIGHTID;
		$.each(data, function(index, value) {
			var deptid = value.DEPID;
			if (dRightIDs != undefined
					&& dRightIDs.indexOf(deptid) >= 0) {
				value['checked'] = 'true';
			} else
				value['checked'] = 'false';
		});
		if (deptTree != null)
			deptTree.destroy();
		deptTree = $.fn.zTree.init($("#deptTree"),
				deptTreeSet, data);
		deptTree.expandAll(true);
	}
	$(document).ready(function() {
		//var userTree = null;

			//加载部门和人员树
			$.ajax({
				async : false,
				cache : false,
				type : 'POST',
				dataType : "json",
				url : "${ctx}/user/getRoleTree",
				error : function() {
					notyError('人员数据加载失败!');
				},
				success : function(data) {
					roleTree = $.fn.zTree.init($("#roleTree"),roleTreeSet, data);
					roleTree.expandNode(roleTree
							.getNodeByTId("roleTree_1"), true,
							false, false);
				}
			});



			//权限复制按钮点击事件处理
			$("#btn_copy").click(function(e) {
				if (selRoleId == "") {
					notyWarning("请先选择一个角色!");
					return false;
				}
				copyNodes = rightTree.getNodes();
				//notyInfo("已复制勾选内容，可选择一个人员进行粘贴!");
				notyInfo("已复制勾选内容，可选择一个角色进行粘贴!");
			});

			//权限粘贴按钮点击事件处理
			$("#btn_paste").click(
					function(e) {
						if (selRoleId == "") {
							notyWarning("请先选择一个角色!");
							return false;
						}
						if (rightTree != null)
							rightTree.destroy();
						rightTree = $.fn.zTree.init(
								$("#rightTree"), rightTreeSet,
								copyNodes);
						rightTree.expandAll(true);
					});

			//保存按钮点击事件处理
			$("#btn_save").click(function (e) {
				if (selWfroleID == "") {
					notyWarning("请先选择一个角色!");
					return false;
				}
				var selRoleNodes = [];
				/*var roleNodes = roleTree.getCheckedNodes();	//获得已选中用户
				$.each(roleNodes, function (index, value) {
					var isParent = value.ISPARENT;
					if(isParent == 'false'){
						var node = {'roleId': value.ID};
						selRoleNodes.push(node);
					}
				});*/
				var node = {'roleId': selWfroleID};
				selRoleNodes.push(node);
				//获得已选择的菜单
				var rightNodes = rightTree.getCheckedNodes();
				var selRightNodes = [];
				$.each(rightNodes, function (index, value) {
					var node = {'RIGHTID': value.RIGHTID};
					node['DATARIGHTID'] = value.DATARIGHTID;
					selRightNodes.push(node);
				});
				var jsonObj = jQuery.parseJSON('{"roleId":"' + selRoleId + '"}');
				jsonObj['roleIds'] = JSON.stringify(selRoleNodes);
				jsonObj['rightIds'] = JSON.stringify(selRightNodes);
				$.ajax({
					async: false,
					cache: false,
					type: 'POST',
					data: $.param(jsonObj),
					dataType: "json",
					url: "${ctx}/right/saveRoleRight",
					error: function () {
						notyError('数据提交失败!');
					},
					success: function (data) {
						notySuccess(data.message);
					}
				});

			});

			// 初始化流程角色列表
			$("#wfRoleTable").DataTable({
				"sDom" : "<'row-fluid'<'pull-left filterInput'f>>t<'row-fluid bgpage'<'span4'il><'span7'<'pull-right'p>>>",
				iDisplayStart: 0,
				iDisplayLength: 10,
				bAutoWidth: false,
				//"sScrollY": 450, //高度
				fnDrawCallback : wfroleRowSeltListener,
				sAjaxSource : path + "/role/getAllRole",//获取列表数据url
				oLanguage : {
					"sSearch" : "角色名称："
				},
				"bSort": true,
				"order": [
					[1, "asc"]
				],
				//table 表头
				aoColumns: [
					{'mDataProp':'ROLE_ID' , 'sTitle' : '角色编码','sClass' : 'center','bVisible' : false},
					{'mDataProp':'ROLE_ORDER' ,'sTitle' : '排列顺序','sClass' : 'center',"sDefaultContent" : "", 'sWidth' : '20%'},
					{'mDataProp':'ROLE_NAME' ,'sTitle' : '角色名称','sClass' : 'center',"sDefaultContent" : "", 'sWidth' : '40%'},
					{'mDataProp':'MEMO' ,'sTitle' : '备注','sClass' : 'center',"sDefaultContent" : "", 'sWidth' : '40%'}
				],
				//渲染某列格式
				aoColumnDefs: [
					{
						aTargets: ["_all"],	//指向某一列，0为第一列
						mRender: function (data, type, row) {
							var subData = data;
							if (data instanceof Object) {
								try {
									return new Date(data.time).Format("yyyy-MM-dd hh:mm:ss");
								} catch (e) {
									subData = data;
								}
							}
							return subData;
						}
					}
				],
				//向后台提交url携带的参数
				fnServerParams : function(aoData) {
					aoData.push({"name":"sflccx","value":$('#sflcSel option:selected').val()});
				}
			});
	});

</script>

</head>
<body>
<div class="bg-white item_title">
	权限管理
</div>
<div class="bg-white">
	<div class="page-content case-info-content">
		<div class="row" >
					 	 <!-- 部门人员树 -->
					 	 <div  class="col-xs-6">
						 	 <%--<div class="box" >
						 	 	<div class="box-header">
									<span><h4><i class="fa fa-users"></i> 角色组树</h4></span>
								</div>
								<div class="box-content">
							 	 	<ul id="roleTree" class="ztree"></ul>
							     </div>
						 	 </div>--%>
								 <div class="box">
									 <div class="box-header" style="margin-bottom: 10px;">
										 <span><h4><i class="fa fa-users"></i>角色组列表</h4></span>
									 </div>
									 <div class="box-content">
										 <%--<div class="self_table_search">--%>
										 <%--<label class="control-label"><span class="required">*</span>角色类型：</label>--%>
										 <%--<select id="sflcSel" onchange="sflcChange();" class="form-control input-sm" >--%>
										 <%--<option value="">所有</option>--%>
										 <%--<option value="1">流程角色</option>--%>
										 <%--<option value="0">普通角色</option>--%>
										 <%--</select>--%>
										 <%--</div>--%>
										 <table id="wfRoleTable" class="table table-striped table-bordered self_table table-hover display">
										 </table>
									 </div>
								 </div>
					 	 </div>
					 	 <!-- 菜单功能树 -->
					 	 <div  class="col-xs-6">
					 	 	<div class="box">
						 	 	<div class="box-header" style="height: 34px;margin-bottom: 10px;">
									<span><h4><i class="fa fa-building"></i> 菜单树</h4></span>
									<div class="box-icon" style="float: right;">
										<%--<a id="btn_copy" class="btn btn-md btn-primary" href="javascript:void(0);" title="复制选中的权限"><i class="fa fa-copy"></i> 复制</a>&nbsp;&nbsp;--%>
										<%--<a id="btn_paste" class="btn btn-md btn-warning" href="javascript:void(0);" title="粘贴已复制的权限"><i class="fa fa-paste"></i> 粘贴</a>&nbsp;&nbsp;--%>
										<a id="btn_save" class="btn btn-md btn-success" href="javascript:void(0);" title="保存选中的权限">保存</a>&nbsp;&nbsp;
									</div>
								</div>
								<div class="box-content" style="min-height: 550px;">
							 	 	<ul id="rightTree" class="ztree"></ul>
							    </div>
							</div>
					 	 </div>
					 
			</div>
		
	</div>
</div>
	<div id="deptContent" class="deptContent"
		style="display: none; position: absolute; background-color: #ffffff;">

		<ul id="deptTree" class="ztree" style="margin-top: 0; width: 160px;"></ul>

	</div>

</body>
</html>
